package com.frame.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.frame.common.core.entity.SysRole;
import com.frame.common.core.security.entity.SecurityUser;
import com.frame.common.core.security.utils.SecurityUtils;
import com.frame.common.core.security.utils.TokenUtil;
import com.frame.db.util.Condition;
import com.frame.db.util.Query;
import com.frame.security.service.ISysRoleService;
import com.frame.security.service.ISysUserService;
import com.frame.security.service.handle.SysPermissionService;
import com.frame.stant.constans.UserConstants;
import com.frame.stant.utils.R;
import com.frame.stant.utils.ServletUtils;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * 角色信息
 *
 * @author ruoyi
 */
@Api(tags = "角色")
@RestController
@RequestMapping("/system/role")
@AllArgsConstructor
public class SysRoleController  {

    private final ISysRoleService roleService;
    private final TokenUtil tokenService;
    private final SysPermissionService permissionService;
    private final ISysUserService userService;

    @PreAuthorize("@custom.hasAnyAuthority('system:role:list')")
    @GetMapping("/list")
    public R list(SysRole role, Query query) {
        IPage<SysRole> list = roleService.selectRoleList(Condition.page(query),role);
        return R.success(list);
    }

//    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
//    @PreAuthorize("@custom.hasAnyAuthority('system:role:export')")
//    @GetMapping("/export")
//    public R export(SysRole role) {
//        List<SysRole> list = roleService.selectRoleList(role);
//        ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
//        return util.exportExcel(list, "角色数据");
//    }

    /**
     * 根据角色编号获取详细信息
     */
    @PreAuthorize("@custom.hasAnyAuthority('system:role:query')")
    @GetMapping(value = "/{roleId}")
    public R getInfo(@PathVariable Long roleId) {
        return R.success(roleService.getById(roleId));
    }

    /**
     * 新增角色
     */
    @PreAuthorize("@custom.hasAnyAuthority('system:role:add')")
//    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@Validated @RequestBody SysRole role) {
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
            return R.error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
            return R.error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(SecurityUtils.getUsername());
        return R.success(roleService.insertRole(role));

    }

    /**
     * 修改保存角色
     */
    @PreAuthorize("@custom.hasAnyAuthority('system:role:edit')")
//    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@Validated @RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
            return R.error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
            return R.error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(SecurityUtils.getUsername());

        if (roleService.updateRole(role) > 0) {
            // 更新缓存用户权限
            SecurityUser loginUser = tokenService.getCurrentUser(ServletUtils.getRequest());
            if (Objects.nonNull(loginUser.getUser()) && !loginUser.getUser().isAdmin()) {
                loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
                loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
                tokenService.setLoginUser(loginUser);
            }
            return R.success();
        }
        return R.error("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
    }

    /**
     * 修改保存数据权限
     */
    @PreAuthorize("@custom.hasAnyAuthority('system:role:edit')")
//    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public R dataScope(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        return R.success(roleService.authDataScope(role));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@custom.hasAnyAuthority('system:role:edit')")
//    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public R changeStatus(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        role.setUpdateBy(SecurityUtils.getUsername());
        return R.success(roleService.updateById(role));
    }

    /**
     * 删除角色
     */
    @PreAuthorize("@custom.hasAnyAuthority('system:role:remove')")
//    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public R remove(@PathVariable Long[] roleIds) {
        return R.success(roleService.deleteRoleByIds(roleIds));
    }

    /**
     * 获取角色选择框列表
     */
    @PreAuthorize("@custom.hasAnyAuthority('system:role:query')")
    @GetMapping("/optionselect")
    public R optionselect() {
        return R.success(roleService.selectRoleAll());
    }
}
